package logic

import (
	"context"
	"course-admin/model"
	"errors"

	"course-admin/userrpc/internal/svc"
	"course-admin/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 发布
func (l *GoodsAddLogic) GoodsAdd(in *userrpc.GoodsAddRequest) (*userrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User

	if err := findUser.FindUserById(model.DB, in.UserId); err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("请登录")
	}
	class := model.Class{
		ClassName: in.ClassName,
	}
	if err := class.FindCreate(model.DB, in.ClassName); err != nil {
		return nil, errors.New("分类创建失败")
	}
	goods := model.Goods{
		GoodsName:    in.GoodsName,
		GoodsPrice:   in.GoodsPrice,
		GoodsContent: in.GoodsContent,
		Cid:          int(class.ID),
		UserId:       int(in.UserId),
	}

	if err := goods.GoodsAdd(model.DB); err != nil {
		return nil, errors.New("发布失败")
	}
	return &userrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
